package org.cfd.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import java.util.List;
import org.cfd.entity.Orders;
import org.cfd.service.OrdersService;
import org.cfd.utils.Code;
import org.cfd.utils.Result;
import org.springframework.web.bind.annotation.*;

/**
 * 订单控制器
 *
 * @author rjs
 */
@RestController
@CrossOrigin
@RequestMapping("/order")
public class OrderController {

  @Resource private OrdersService orderService;

  /**
   * 保存订单
   *
   * @param orders 订单对象
   * @return 响应实体（保存成功或失败）
   */
  @PostMapping
  public Result saveOrder(@RequestBody Orders orders) {
    if (orderService.save(orders)) {
      return new Result(Code.ADD_SUCCESS, "订单保存成功", orders);
    } else {
      return new Result(Code.ADD_ERROR, "订单保存失败");
    }
  }

  /**
   * 更新订单
   *
   * @param orders 订单对象
   * @return 响应实体（更新成功或失败）
   */
  @PutMapping
  public Result updateOrder(@RequestBody Orders orders) {
    if (orderService.updateById(orders)) {
      return new Result(Code.UPDATE_SUCCESS, "订单更新成功", orders);
    } else {
      return new Result(Code.UPDATE_ERROR, "订单更新失败");
    }
  }

  /**
   * 根据订单ID获取订单
   *
   * @param orders 订单对象
   * @return 响应实体（获取成功或失败）
   */
  @GetMapping
  public Result getOrderById(@RequestBody Orders orders) {
    Orders orderInfo = orderService.getById(orders.getId());
    if (orderInfo != null) {
      return new Result(Code.SELECT_SUCCESS, "订单获取成功", orderInfo);
    } else {
      return new Result(Code.SELECT_ERROR, "订单获取失败");
    }
  }

  /**
   * 根据用户ID获取订单
   *
   * @param id 用户ID
   * @return 响应实体（获取成功或失败）
   */
  @GetMapping("/{id}")
  public Result getOrdersByUserId(@PathVariable Integer id) {
    QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("user_id", id);
    List<Orders> orderList = orderService.list(queryWrapper);
    if (!orderList.isEmpty()) {
      return new Result(Code.SELECT_SUCCESS, "订单获取成功", orderList);
    } else {
      return new Result(Code.SELECT_ERROR, "订单获取失败");
    }
  }

  /**
   * 根据订单ID删除订单
   *
   * @param orders 订单对象
   * @return 响应实体（删除成功或失败）
   */
  @DeleteMapping("/delete")
  public Result deleteOrdersById(@RequestBody Orders orders) {
    if (orderService.removeById(orders.getId())) {
      return new Result(Code.DELETE_SUCCESS, "订单删除成功", orders);
    } else {
      return new Result(Code.DELETE_ERROR, "订单删除失败");
    }
  }
}
